#include "PaintListWidget.h"
#include "ui_PaintListWidget.h"

PaintListWidget::PaintListWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PaintListWidget)
{
    ui->setupUi(this);
}

PaintListWidget::~PaintListWidget()
{
    QGridLayout *layoutCls= static_cast<QGridLayout *>(ui->scrollAreaWidgetContents->layout());
    for(QList<SketchWidget *>::iterator it = ListWidget.begin();it!=ListWidget.end();++it)
    {
        layoutCls->removeWidget(*it);
        disconnect(*it,&SketchWidget::OpenShow,this,&PaintListWidget::OpenShow);
        disconnect(*it,&SketchWidget::DeleteDown,this,&PaintListWidget::DeleteDown);
        delete *it;
        *it = nullptr;
    }
    ListWidget.clear();
    delete layoutCls;
    layoutCls = nullptr;

    delete ui;
}

void PaintListWidget::ListWidgetInit(const QMap<QString,QPair<QString,QString>> & image_text)
{
    // 清空
    QGridLayout *layoutCls= static_cast<QGridLayout *>(ui->scrollAreaWidgetContents->layout());
    for(QList<SketchWidget *>::iterator it = ListWidget.begin();it!=ListWidget.end();++it)
    {
        layoutCls->removeWidget(*it);
        disconnect(*it,&SketchWidget::OpenShow,this,&PaintListWidget::OpenShow);
        disconnect(*it,&SketchWidget::DeleteDown,this,&PaintListWidget::DeleteDown);
        delete *it;
        *it = nullptr;
    }
    ListWidget.clear();
    delete layoutCls;
    layoutCls = nullptr;
    QGridLayout *layoutNew = new QGridLayout(ui->scrollAreaWidgetContents);
    layoutNew->setSpacing(6);
    layoutNew->setContentsMargins(4, 4, 4, 4);
    layoutNew->setObjectName(QString::fromUtf8("layoutNew"));
    ui->scrollAreaWidgetContents->setLayout(layoutNew);

    // 初始化
    for(auto it = image_text.begin();it!=image_text.end();++it)
    {
        SketchWidget *testWidget = new SketchWidget(it.key());
        connect(testWidget,&SketchWidget::OpenShow,this,&PaintListWidget::OpenShow);
        connect(testWidget,&SketchWidget::DeleteDown,this,&PaintListWidget::DeleteDown);
        if(testWidget->setTagImagePath(APPPATH + "/" + PAINTFILE::DIRNAME + "/" + it.value().first))
            ListWidget.append(testWidget);
        else
            delete testWidget;
        testWidget=nullptr;
    }
    QGridLayout *layoutOld = static_cast<QGridLayout *>(ui->scrollAreaWidgetContents->layout());
    bool once = true;
    for(QList<SketchWidget *>::iterator it = ListWidget.begin();it!=ListWidget.end();++it)
    {
        if(once)
        {
            once = false;
            layoutOld->addWidget(*it,0,0);
        }
        else
        {
            if(layoutOld->columnCount() < 3)
                layoutOld->addWidget(*it,layoutOld->rowCount()-1,layoutOld->columnCount());
            else
                layoutOld->addWidget(*it);
        }
    }
    layoutOld = nullptr;
}
